package com.quantoeugasto.controle;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.quantoeugasto.entidade.Usuario;
import com.quantoeugasto.servico.BackupService;
import com.quantoeugasto.servico.UsuarioService;

@Component
public class FileUpload extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");

		try {

			ApplicationContext context = WebApplicationContextUtils
					.getWebApplicationContext(request.getSession()
							.getServletContext());

			UsuarioService usuarioService = (UsuarioService) context
					.getBean("usuarioService");
			BackupService backupService = (BackupService) context
					.getBean("backupService");

			ServletFileUpload upload = new ServletFileUpload();

			FileItemIterator iterator = upload.getItemIterator(request);
			while (iterator.hasNext()) {
				FileItemStream item = iterator.next();
				InputStream stream = item.openStream();

				if (!item.isFormField()) {

					Usuario usuario = new Usuario(request.getSession()
							.getAttribute("usuario").toString());
					usuario = usuarioService.consultar(usuario);
					backupService.restaurarBackup(stream, usuario);
				}
			}
			
			System.out.println("Dados restaurados!");

			response.getOutputStream().write(
					"{success:true}".getBytes(Charset.forName("UTF-8")));
		} catch (Exception ex) {
			response.getOutputStream().write(
					("{success:false,msg=\"" + ex.getMessage() + "\"}")
							.getBytes(Charset.forName("UTF-8")));
		}

		response.getOutputStream().flush();
		response.getOutputStream().close();
	}
}